package com.example.minademo;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.example.minademo.interfaces.IMsgCallback;

import android.util.Log;

public class ClientMinaHandler extends IoHandlerAdapter {

	public static final String TAG = "ClientMinaHandler";

	private IMsgCallback mCallback;

	public ClientMinaHandler(IMsgCallback callback) {

		mCallback = callback;
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {

		super.sessionCreated(session);
		System.out.println("sessionCreated~");
		if (null != mCallback) {

			mCallback.clientReceiveMsg("sessionCreated~");
		}
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		super.sessionOpened(session);
		if (null != mCallback) {

			mCallback.clientReceiveMsg("sessionOpened~");
		}
		System.out.println("sessionOpened~");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		super.sessionClosed(session);
		if (null != mCallback) {

			mCallback.clientReceiveMsg("sessionClosed~");
		}
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		// TODO Auto-generated method stub
		super.sessionIdle(session, status);
		if (null != mCallback) {

			mCallback.clientReceiveMsg("sessionIdle~");
		}
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {

		super.exceptionCaught(session, cause);
		System.out.println("exceptionCaught~");
		if (null != mCallback) {

			mCallback.clientReceiveMsg("exceptionCaught~");
		}
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {

		super.messageReceived(session, message);

		String rcvMsg = message.toString();

		Log.d(TAG, "client receive msg form sever:" + rcvMsg);

		System.out.println("receive msg from server: " + rcvMsg);

		if (null != mCallback) {

			mCallback.clientReceiveMsg(rcvMsg);
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {

		super.messageSent(session, message);

		Log.d(TAG, "client send msg to sever:" + message.toString());
		if (null != mCallback) {

			mCallback.clientReceiveMsg("client send msg to sever:"
					+ message.toString());
		}
		System.out.println("send msg to server: " + message.toString());
	}

}
